#include "udp_server.hpp"
#include "err.hpp"

#include <string>
#include <memory>
#include <cerrno>
#include <cstring>

#include <cstdio>
#include <cstring>

#include "daemon.hpp"


using namespace my_server;

static void usage(const char* port)
{
    std::cout<<"USAGE:\n\t"<<port<<" serverip\n"<<std::endl;
}

std::string Task(std::string str) //大小写转换
{
    for(auto &c:str)
    {
        if(c>=97 && c<=122) //小写转大写
            c -= 32;
        else if(c>=65 && c<=90) //大写转小写
            c += 32;
    }
    std::cout<<str<<std::endl;
    return str;
}

static bool isPass(const std::string& str)
{
    if(str.find("mv") != std::string::npos ) return true;
    else if(str.find("rm") != std::string::npos ) return true;
    else if(str.find("kill") != std::string::npos ) return true;
    else if(str.find("while") != std::string::npos ) return true;

    return false;
}

std::string excuteCommand(std::string str) //服务器命令解释
{
    //1.检查命令是否安全
    if(isPass(str)) return "Dangerous Command!"; //判断命令是否安全

    //2.运行命令
    FILE* ret = popen(str.c_str(),"r"); //运行指令 返回值只读
    //if(ret == nullptr) return "The Operating Environment Is Abnormal!";;

    //处理返回值
    str.clear();
    char line[1024] = {0};
    while(fgets(line,1024,ret) != nullptr) str+=line;
    fclose(ret);
    if(str.size() == 0) str.append("Command Exception Or Does Not Exist!");
    return str;
}

int main(int argc,char* argv[])
{
    uint16_t port = 8088;
    if(argc == 2)
    {
        port = htons(atoi(argv[1]));
    }
    else if(argc > 2)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    //std::unique_ptr<Server> server(new Server(Task,port)); //大小写判断
    // std::unique_ptr<Server> server(new Server(excuteCommand,port)); ///命令行解读

    // server->InitServer();
    // server->start();

    daemon(); //守护进程化

    std::unique_ptr<Server> server(new Server(port));
    server->start();
    
    return 0;
}